package cn.study.luckyinfrastructure.gateway.iml;

import cm.study.config.enums.LdExeceptionEnum;
import cm.study.config.util.AssertUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.study.luckyclient.dto.query.ActivityListByParamQuery;
import cn.study.luckyclient.dto.query.ActivityRuleByParamQuery;
import cn.study.luckydomain.activity.ActivityEntity;
import cn.study.luckydomain.activityrule.ActivityRuleEntity;
import cn.study.luckydomain.gateway.ActivityGateway;
import cn.study.luckydomain.gateway.ActivityRuleGateway;
import cn.study.luckyinfrastructure.convertor.ActivityRuleConvertor;
import cn.study.luckyinfrastructure.gateway.iml.dataObject.ActivityRuleDB;
import cn.study.luckyinfrastructure.gateway.iml.mapper.ActivityRuleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@AllArgsConstructor
public class ActivityRuleGatewayImpl implements ActivityRuleGateway {
    private final ActivityRuleMapper activityRuleMapper;

    @Override
    public ActivityRuleEntity add(ActivityRuleEntity entity) {

        ActivityRuleDB activityRuleDB = ActivityRuleConvertor.toActivityRuleDB(entity);
        log.info("信息"+activityRuleDB);
        int insert=activityRuleMapper.insert(activityRuleDB);

        AssertUtil.isTrue( insert<= 0, LdExeceptionEnum.ADD_ERROR.getDescription());

        return ActivityRuleConvertor.toEntity(activityRuleDB);
    }

    @Override
    public List<ActivityRuleEntity> list(ActivityRuleByParamQuery query) {
        LambdaQueryWrapper<ActivityRuleDB> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(query.getActivityId()!=null,ActivityRuleDB::getActivityId,query.getActivityId());
        List<ActivityRuleDB> list = activityRuleMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        return new Page<ActivityRuleDB>()
                .setRecords(list)
                .convert(ActivityRuleConvertor::toEntity)
                .getRecords();
    }

    @Override
    public void deleteByActivityId(Long activityId) {
        QueryWrapper<ActivityRuleDB> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activityId",activityId);
        activityRuleMapper.delete(queryWrapper);
    }
}
